<template>
	
	<view class="profile-container">
		<!-- 已登录状态 -->
		<view>
		<!-- 顶部用户信息卡片 -->
		<view class="user-info-card">
			<view class="user-background">
				<image src="https://i.ibb.co/DHSJKYzb/shouyebg.jpg" mode="aspectFill" class="bg-image"></image>
				<view class="bg-overlay"></view>
			</view>
			
			<view class="user-content">
				<!-- 头像和基本信息 -->
				<view class="user-header">
					<view class="avatar-container" @click="changeAvatar">
						<image :src="userInfo.avatar" mode="aspectFill" class="user-avatar"></image>
						<view class="avatar-edit-icon">
							<text class="edit-text">编辑</text>
						</view>
					</view>
					<view class="user-basic-info">
						<text class="username">{{ userInfo.nickname }}</text>
						<text class="user-id">ID: {{ userInfo.userId }}</text>
						<view class="vip-badge" v-if="userInfo.isVip">
							<text class="vip-text">VIP</text>
						</view>
					</view>
				</view>
				
				<!-- 用户统计信息 -->
				<view class="stats-info">
					<view class="stats-item">
						<text class="stats-value">{{ userInfo.photoCount }}</text>
						<text class="stats-label">生成照片</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 充值中心入口 - 暂时隐藏 -->
		<!-- <view class="recharge-section">
			<view class="recharge-card" @click="goToRecharge">
				<view class="recharge-icon">
					<text class="icon-recharge">💎</text>
				</view>
				<view class="recharge-content">
					<text class="recharge-title">充值中心</text>
					<text class="recharge-desc">购买积分，畅享AI拍照</text>
				</view>
				<view class="recharge-arrow">
					<text class="arrow">></text>
				</view>
			</view>
		</view> -->
		
		<!-- 功能菜单区域 -->
		<view class="menu-section">
			<!-- 我的相册 -->
			<view class="menu-group">
				<text class="group-title">我的作品</text>
				<view class="menu-item" @click="goToAlbum">
					<view class="menu-icon album-icon">
						<text class="icon">📷</text>
					</view>
					<view class="menu-content">
						<text class="menu-title">我的相册</text>
						<text class="menu-desc">查看我生成的所有照片</text>
					</view>
					<view class="menu-arrow">
						<text class="arrow">></text>
					</view>
				</view>
			</view>
			
			<!-- 我的记录 -->
			<view class="menu-group">
				<text class="group-title">我的记录</text>
				<!-- 兑换券记录 -->
				<view class="menu-item" @click="goToCouponHistory">
					<view class="menu-icon coupon-icon">
						<text class="icon">🎟️</text>
					</view>
					<view class="menu-content">
						<text class="menu-title">兑换券记录</text>
						<text class="menu-desc">查看我的兑换券历史</text>
					</view>
					<view class="menu-arrow">
						<text class="arrow">></text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部空白，避免被tabbar遮挡 -->
		<view class="bottom-space"></view>
		
		<!-- 椭圆形导航栏 -->
		<EllipseTabBar />
		
		</view>
	</view>
</template>

<script>
import userApi from '@/api/ai-trip/user.js'
// 导入椭圆形导航栏组件
import EllipseTabBar from '@/components/ai-trip/EllipseTabBar.vue'

export default {
	components: {
		EllipseTabBar 
	},
	data() {
		return {
			isLoggedIn: false, // 登录状态
			userInfo: {
				avatar: 'https://i.ibb.co/9m20f88T/ailvpai.jpg',
				nickname: '微信用户',
				userId: '',
				isVip: false,
				credits: 0,
				photoCount: 0
			},
			uploading: false,
			albumCount: 12, // 添加相册照片数量
			showPhoneAuth: false, // 是否显示手机号授权按钮
			wxCode: '' // 微信登录code
		}
	},
	onLoad() {
		// 获取状态栏高度
		const systemInfo = uni.getSystemInfoSync();
		this.statusBarHeight = systemInfo.statusBarHeight;
		
		// 检查登录状态
		this.checkLoginStatus();
		
		console.log('个人中心页面加载完成');
	},
	
	onShow() {
		console.log('个人中心页面显示');
		// 每次显示页面时刷新用户信息
		const token = uni.getStorageSync('token');
		if (token) {
			// 动态引入 getUserInfo
			import('@/api/ai-trip/auth.js').then(({ getUserInfo }) => {
				getUserInfo(token).then(res => {
					if (res && res.code === 200 && res.data) {
						this.userInfo = {
							avatar: res.data.avatar || 'https://cdn.zhzfpn.cn/dong/image/ailvpai.jpg',
							nickname: res.data.nickname || '微信用户',
							userId: res.data.id || '未知用户',
							isVip: res.data.is_vip || false,
							credits: res.data.credits || 0,
							photoCount: res.data.photoCount || 0
						};
						uni.setStorageSync('userInfo', res.data);
					}
				});
			});
		}
		// 兼容原有登录状态检查
		this.checkLoginStatus();
	},
	methods: {
		// 检查登录状态
		checkLoginStatus() {
			const isLoggedIn = uni.getStorageSync('isLoggedIn');
			const token = uni.getStorageSync('token');
			const userInfo = uni.getStorageSync('userInfo');
			
			if (isLoggedIn && token && userInfo) {
				this.isLoggedIn = true;
				this.loadUserInfo(userInfo);
			} else {
				this.isLoggedIn = false;
			}
		},
		
		// 加载用户信息
		loadUserInfo(userInfo) {
			this.userInfo = {
				avatar: userInfo.avatar || 'https://cdn.zhzfpn.cn/dong/image/ailvpai.jpg',
				nickname: userInfo.nickname || '微信用户',
				userId: userInfo.id || '未知用户',
				isVip: userInfo.is_vip || false,
				credits: userInfo.credits || 0,
				photoCount: userInfo.photoCount || 0 // 如果后端有提供的话
			};
		},
		
		// 更换头像 - 简化版本
		async changeAvatar() {
			console.log('点击了更换头像');
			
			if (this.uploading) {
				console.log('正在上传中，跳过');
				return;
			}

			try {
				// 显示选择来源的弹窗
				const actionRes = await uni.showActionSheet({
					itemList: ['拍照', '从相册选择']
				});

				let sourceType;
				if (actionRes.tapIndex === 0) {
					sourceType = ['camera'];
				} else {
					sourceType = ['album'];
				}

				// 选择图片 - 使用Promise包装
				const chooseImage = () => {
					return new Promise((resolve, reject) => {
						uni.chooseImage({
							count: 1,
							sizeType: ['compressed'],
							sourceType: sourceType,
							success: (res) => {
								console.log('选择图片成功:', res);
								resolve(res);
							},
							fail: (err) => {
								console.log('选择图片失败:', err);
								reject(err);
							}
						});
					});
				};

				const chooseRes = await chooseImage();
				console.log('选择图片结果:', chooseRes);

				// 检查是否成功选择了图片
				if (!chooseRes.tempFilePaths || chooseRes.tempFilePaths.length === 0) {
					console.log('用户取消选择图片');
					return;
				}

				const tempFilePath = chooseRes.tempFilePaths[0];
				console.log('选择的图片路径:', tempFilePath);
				
				// 显示加载提示
				uni.showLoading({ title: '上传中...' });
				this.uploading = true;
				
				console.log('开始上传并保存头像');

				// 上传并保存头像（一步完成）
				const result = await userApi.uploadAndSaveAvatar(tempFilePath);
				console.log('头像更新完成:', result);

				// 更新本地显示
				this.userInfo.avatar = result.data.avatar;

				// 同时更新本地存储中的用户信息
				const storedUserInfo = uni.getStorageSync('userInfo');
				if (storedUserInfo) {
					storedUserInfo.avatar = result.data.avatar;
					uni.setStorageSync('userInfo', storedUserInfo);
					console.log('已更新本地存储中的头像:', result.data.avatar);
				} else {
					console.warn('本地存储中未找到用户信息');
				}

				uni.showToast({
					title: '头像更新成功',
					icon: 'success'
				});

			} catch (error) {
				// 用户取消操作时不显示错误提示
				if (error.errMsg && error.errMsg.includes('cancel')) {
					console.log('用户取消了操作');
					return;
				}
				
				console.error('更换头像失败:', error);
				uni.showToast({
					title: error.message || '更换头像失败',
					icon: 'none'
				});
			} finally {
				console.log('清理上传状态');
				uni.hideLoading();
				this.uploading = false;
			}
		},
		
		
		
			goToCouponHistory() {
		uni.navigateTo({
			url: '/pages/ai-trip/user/coupon/coupon',
			success: () => {
				console.log('跳转到兑换券历史记录页面成功');
			},
			fail: (err) => {
				console.error('跳转到兑换券历史记录页面失败:', err);
				uni.showToast({
					title: '页面跳转失败，请重试',
					icon: 'none',
					duration: 2000
				});
			}
		});
	},
		
		goToAlbum() {
			uni.navigateTo({
				url: '/pages/ai-trip/my_photo/index',
				success: () => {
					console.log('跳转到我的相册页面成功');
				},
				fail: (err) => {
					console.error('跳转到我的相册页面失败:', err);
			uni.showToast({
						title: '页面跳转失败，请重试',
						icon: 'none',
						duration: 2000
			});
				}
			});
		},
		
		// 调用AI旅拍登录函数
		async goToLogin() {
			try {
				console.log('开始AI旅拍登录流程');
				
				// 显示加载提示
				uni.showLoading({
					title: '登录中...',
					mask: true
				});
				
				// 动态导入AI旅拍认证模块
				const { wxLogin, login, saveLoginInfo } = await import('@/api/ai-trip/auth.js');
				
				// 第一步：获取微信登录code
				const code = await wxLogin();
				console.log('微信登录code获取成功:', code);
				
				// 第二步：获取手机号授权
				// 这里需要用户手动授权，通过button的open-type="getPhoneNumber"
				uni.hideLoading();
				
				// 显示手机号授权提示
				uni.showModal({
					title: '需要手机号授权',
					content: '为了完成登录，需要获取您的手机号信息',
					confirmText: '授权登录',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							// 用户同意授权，显示授权按钮
							this.showPhoneAuth = true;
							this.wxCode = code; // 保存code供后续使用
						}
					}
				});
				
			} catch (error) {
				console.error('登录失败:', error);
				uni.hideLoading();
				
				let errorMessage = '登录失败，请重试';
				if (error.message) {
					errorMessage = error.message;
				}
				
				uni.showToast({
					title: errorMessage,
					icon: 'none',
					duration: 3000
				});
			}
		},
		


		
		// 显示退出登录确认框
		showLogoutConfirm() {
			uni.showModal({
				title: '退出登录',
				content: '确定要退出登录吗？',
				confirmText: '退出登录',
				confirmColor: '#ff6b6b',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						this.logout();
					}
				}
			});
		}
	}
}
</script>

<style scoped>
.profile-container {
	width: 100%;
	min-height: 100vh;
	background: linear-gradient(180deg, #f0f8ff 0%, #e6f3f7 50%, #fff5f0 100%);
}

/* 未登录状态样式 */
.login-guide {
	position: relative;
	width: 100%;
	min-height: 100vh;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.guide-background {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
}

.welcome-content {
	position: relative;
	z-index: 3;
	width: 100%;
	padding: 60rpx 40rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.app-logo {
	width: 120rpx;
	height: 120rpx;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 40rpx;
	backdrop-filter: blur(20rpx);
	border: 2rpx solid rgba(255, 255, 255, 0.3);
}

.logo-icon {
	font-size: 60rpx;
}

.welcome-title {
	font-size: 48rpx;
	font-weight: 600;
	color: white;
	margin-bottom: 16rpx;
	text-align: center;
	text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
}

.welcome-subtitle {
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.8);
	margin-bottom: 60rpx;
	text-align: center;
	text-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.3);
}

.feature-cards {
	width: 100%;
	margin-bottom: 60rpx;
}

.feature-card {
	background: rgba(255, 255, 255, 0.15);
	backdrop-filter: blur(20rpx);
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border: 1rpx solid rgba(255, 255, 255, 0.2);
	display: flex;
	align-items: center;
}

.feature-icon {
	font-size: 40rpx;
	margin-right: 24rpx;
}

.feature-title {
	font-size: 32rpx;
	font-weight: 600;
	color: white;
	margin-bottom: 8rpx;
	display: block;
}

.feature-desc {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.8);
}

.login-actions {
	width: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.login-btn {
	width: 100%;
	height: 88rpx;
	background: linear-gradient(135deg, #5dade2 0%, #58d68d 100%);
	border-radius: 44rpx;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 20rpx;
	box-shadow: 0 8rpx 32rpx rgba(93, 173, 226, 0.3);
	transition: all 0.3s ease;
}

.login-btn:active {
	transform: translateY(2rpx) scale(0.98);
}

/* 手机号授权按钮样式 */
.phone-auth-btn {
	width: 100%;
	height: 88rpx;
	background: linear-gradient(135deg, #ff9a85 0%, #ff6b6b 100%);
	border-radius: 44rpx;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 20rpx;
	box-shadow: 0 8rpx 32rpx rgba(255, 154, 133, 0.3);
	transition: all 0.3s ease;
}

.phone-auth-btn:active {
	transform: translateY(2rpx) scale(0.98);
}

.btn-text {
	font-size: 32rpx;
	font-weight: 600;
	color: white;
}

.login-tip {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.7);
	text-align: center;
}

/* 用户信息卡片 */
.user-info-card {
	position: relative;
	margin: 40rpx 30rpx;
	border-radius: 24rpx;
	overflow: hidden;
	box-shadow: 0 8rpx 32rpx rgba(74, 144, 226, 0.2);
}

.user-background {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
}

.bg-image {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

.bg-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: linear-gradient(135deg, rgba(74, 144, 226, 0.85) 0%, rgba(86, 200, 216, 0.75) 50%, rgba(255, 154, 133, 0.65) 100%);
}

.user-content {
	position: relative;
	z-index: 2;
	padding: 40rpx 30rpx;
}

.user-header {
	display: flex;
	align-items: center;
	margin-bottom: 30rpx;
}

.avatar-container {
	position: relative;
	margin-right: 30rpx;
}

.user-avatar {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	border: 4rpx solid rgba(255, 255, 255, 0.8);
	object-fit: cover;
}

.avatar-edit-icon {
	position: absolute;
	bottom: -5rpx;
	right: -5rpx;
	width: 40rpx;
	height: 40rpx;
	background: rgba(255, 255, 255, 0.9);
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.edit-text {
	font-size: 18rpx;
	color: #666;
	font-weight: 500;
}

.user-basic-info {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.username {
	font-size: 44rpx;
	font-weight: 600;
	color: white;
	margin-bottom: 8rpx;
	text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
}

.user-id {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.8);
	margin-bottom: 12rpx;
}

.vip-badge {
	width: fit-content;
	background: linear-gradient(135deg, #ff9a85 0%, #ffd180 100%);
	color: white;
	font-size: 20rpx;
	font-weight: 600;
	padding: 6rpx 16rpx;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(255, 154, 133, 0.4);
}

.vip-text {
	letter-spacing: 1rpx;
}

.stats-info {
	display: flex;
	align-items: center;
	justify-content: center;
	background: rgba(255, 255, 255, 0.15);
	backdrop-filter: blur(20rpx);
	-webkit-backdrop-filter: blur(20rpx);
	border-radius: 16rpx;
	padding: 24rpx;
	border: 1rpx solid rgba(255, 255, 255, 0.2);
}

.stats-item {
	text-align: center;
}

.stats-value {
	display: block;
	font-size: 48rpx;
	font-weight: 700;
	color: white;
	margin-bottom: 8rpx;
	text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
}

.stats-label {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.8);
}

/* 充值中心 */
.recharge-section {
	margin: 0 30rpx 40rpx;
}

.recharge-card {
	background: linear-gradient(135deg, #5dade2 0%, #58d68d 100%);
	border-radius: 20rpx;
	padding: 30rpx;
	display: flex;
	align-items: center;
	box-shadow: 0 8rpx 32rpx rgba(93, 173, 226, 0.25);
	transition: all 0.3s ease;
}

.recharge-card:active {
	transform: translateY(2rpx) scale(0.98);
}

.recharge-icon {
	width: 80rpx;
	height: 80rpx;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 24rpx;
	backdrop-filter: blur(10rpx);
	border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.icon-recharge {
	font-size: 36rpx;
}

.recharge-content {
	flex: 1;
}

.recharge-title {
	display: block;
	font-size: 32rpx;
	font-weight: 600;
	color: white;
	margin-bottom: 6rpx;
}

.recharge-desc {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.8);
}

.recharge-arrow {
	width: 40rpx;
	height: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.arrow {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.8);
	font-weight: 600;
}

/* 菜单区域 */
.menu-section {
	margin: 0 30rpx;
}

.menu-group {
	margin-bottom: 40rpx;
}

.group-title {
	display: block;
	font-size: 28rpx;
	font-weight: 600;
	color: #666;
	margin-bottom: 20rpx;
	padding-left: 8rpx;
}

.menu-item {
	background: white;
	border-radius: 16rpx;
	padding: 30rpx;
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	transition: all 0.3s ease;
}

.menu-item:active {
	transform: translateY(1rpx) scale(0.98);
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.12);
}

.menu-item:last-child {
	margin-bottom: 0;
}

.menu-icon {
	width: 80rpx;
	height: 80rpx;
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 24rpx;
}

.album-icon {
	background: linear-gradient(135deg, #ff9a85 0%, #ffa07a 100%);
}

.history-icon {
	background: linear-gradient(135deg, #5dade2 0%, #58d68d 100%);
}

.coupon-icon {
	background: linear-gradient(135deg, #4CAF50 0%, #81C784 100%); /* A green color for coupons */
}


.logout-icon {
	background: linear-gradient(135deg, #ff6b6b 0%, #ff8e8e 100%);
}

.logout-item {
	border: 1rpx solid rgba(255, 107, 107, 0.2);
}

.logout-item:active {
	background: rgba(255, 107, 107, 0.05);
}

.icon {
	font-size: 36rpx;
}

.menu-content {
	flex: 1;
}

.menu-title {
	display: block;
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 6rpx;
}

.menu-desc {
	font-size: 24rpx;
	color: #999;
}

.menu-badge {
	background: linear-gradient(135deg, #ff9a85 0%, #ff6b6b 100%);
	color: white;
	font-size: 20rpx;
	font-weight: 600;
	padding: 4rpx 12rpx;
	border-radius: 12rpx;
	margin-right: 16rpx;
	min-width: 32rpx;
	text-align: center;
	box-shadow: 0 2rpx 8rpx rgba(255, 154, 133, 0.3);
}

.badge-text {
	font-size: 20rpx;
}

.menu-arrow {
	width: 40rpx;
	height: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.bottom-space {
	height: 120rpx;
}


/* 移动端适配 */
@media screen and (max-width: 375px) {
	.user-avatar {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50rpx;
	}
	
	.username {
		font-size: 40rpx;
	}
	
	.balance-value {
		font-size: 42rpx;
	}
}
</style>